package com.gitee.mocoffee.embedredis.spring;

import java.util.Properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.core.io.ClassPathResource;

import com.google.common.base.Strings;

import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import redis.embedded.RedisServer;

/**
 * @author lijia
 */
@FieldDefaults(level = AccessLevel.PRIVATE)
public class EmbedRedisListener implements ApplicationListener<ApplicationEvent> {
    public static final String CONFIG_FILE = "config/application.yml";

    volatile RedisServer server;

    boolean enable;

    Integer port;

    public EmbedRedisListener() {
        YamlPropertiesFactoryBean y = new YamlPropertiesFactoryBean();
        y.setResources(new ClassPathResource(CONFIG_FILE));
        y.afterPropertiesSet();
        Properties conf = y.getObject();
        String enableStr = conf.getProperty("app.embedredis.enable");
        if (!Strings.isNullOrEmpty(enableStr))
            enable = Boolean.parseBoolean(enableStr);

        if (enable) {
            String portStr = conf.getProperty("app.embedredis.port");
            if (!Strings.isNullOrEmpty(portStr))
                port = Integer.parseInt(portStr);
        }
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (enable) {
            if (applicationEvent instanceof ApplicationPreparedEvent) {
                server = port != null && port > 0 ? new RedisServer(port) : new RedisServer();
                server.start();
            } else if (applicationEvent instanceof ContextClosedEvent)
                server.stop();
        }
    }
}
